<?php

require_once __DIR__ . '/../autoload.php';

use Database\Connection;
use ORM\Model;
use examples\models\User;
use examples\models\Post;

// 测试函数
function runTest($name, $callback) {
    echo "\n测试: {$name}\n";
    echo "------------------------\n";
    
    try {
        $result = $callback();
        echo "✅ 测试通过\n";
        return $result;
    } catch (\Exception $e) {
        echo "❌ 测试失败: " . $e->getMessage() . "\n";
        return null;
    }
}

// 加载数据库配置
$config = require_once __DIR__ . '/../config/database.php';

// 创建数据库连接
$connection = Connection::getInstance($config);

// 设置模型的数据库连接
Model::setConnection($connection);

echo "\n开始ORM系统测试\n";
echo "======================\n";

// 测试1: 数据库连接
runTest('数据库连接', function() use ($connection) {
    // 简单的查询测试连接是否正常
    $result = $connection->query("SELECT 1 as test");
    
    if (!$result || !isset($result[0]['test']) || $result[0]['test'] != 1) {
        throw new \Exception("数据库连接测试失败");
    }
    
    echo "数据库连接正常\n";
    return true;
});

// 测试2: 模型创建
$user = runTest('模型创建', function() {
    $user = new User([
        'name' => '测试用户',
        'email' => 'test_' . time() . '@example.com',
        'password' => 'test123'
    ]);
    
    $user->save();
    
    if (!$user->id) {
        throw new \Exception("用户创建失败，未获取到ID");
    }
    
    echo "用户创建成功，ID: {$user->id}\n";
    return $user;
});

// 测试3: 模型查询
runTest('模型查询', function() use ($user) {
    if (!$user || !$user->id) {
        throw new \Exception("跳过测试，因为用户创建失败");
    }
    
    $foundUser = User::find($user->id);
    
    if (!$foundUser) {
        throw new \Exception("未找到用户，ID: {$user->id}");
    }
    
    if ($foundUser->name !== $user->name || $foundUser->email !== $user->email) {
        throw new \Exception("用户数据不匹配");
    }
    
    echo "成功查询到用户: {$foundUser->name}\n";
    return $foundUser;
});

// 测试4: 模型更新
runTest('模型更新', function() use ($user) {
    if (!$user || !$user->id) {
        throw new \Exception("跳过测试，因为用户创建失败");
    }
    
    $foundUser = User::find($user->id);
    
    if (!$foundUser) {
        throw new \Exception("未找到用户，ID: {$user->id}");
    }
    
    $newName = '更新的测试用户_' . time();
    $foundUser->name = $newName;
    $foundUser->save();
    
    // 重新查询验证更新
    $updatedUser = User::find($user->id);
    
    if ($updatedUser->name !== $newName) {
        throw new \Exception("用户更新失败");
    }
    
    echo "用户更新成功: {$updatedUser->name}\n";
    return $updatedUser;
});

// 测试5: 关联关系
$post = runTest('关联关系', function() use ($user) {
    if (!$user || !$user->id) {
        throw new \Exception("跳过测试，因为用户创建失败");
    }
    
    // 创建文章
    $post = new Post([
        'title' => '测试文章_' . time(),
        'content' => '这是一篇测试文章的内容',
        'user_id' => $user->id
    ]);
    
    $post->save();
    
    if (!$post->id) {
        throw new \Exception("文章创建失败");
    }
    
    echo "文章创建成功，ID: {$post->id}\n";
    
    // 测试关联 - 从文章获取用户
    $author = $post->user;
    
    if (!$author || $author->id !== $user->id) {
        throw new \Exception("从文章获取用户失败");
    }
    
    echo "成功从文章获取到作者: {$author->name}\n";
    
    // 测试关联 - 从用户获取文章
    $posts = $user->posts;
    
    if (!$posts || !is_array($posts) || count($posts) === 0) {
        throw new \Exception("从用户获取文章失败");
    }
    
    $found = false;
    foreach ($posts as $p) {
        if ($p->id === $post->id) {
            $found = true;
            break;
        }
    }
    
    if (!$found) {
        throw new \Exception("在用户的文章列表中未找到刚创建的文章");
    }
    
    echo "成功从用户获取到文章列表，共 " . count($posts) . " 篇\n";
    return $post;
});

// 测试6: 模型删除
runTest('模型删除', function() use ($post) {
    if (!$post || !$post->id) {
        throw new \Exception("跳过测试，因为文章创建失败");
    }
    
    $postId = $post->id;
    $post->delete();
    
    // 验证删除
    $deletedPost = Post::find($postId);
    
    if ($deletedPost) {
        throw new \Exception("文章删除失败，仍能查询到ID: {$postId}");
    }
    
    echo "文章删除成功\n";
    return true;
});

// 测试7: 查询构建器
runTest('查询构建器', function() {
    // 创建一些测试数据
    for ($i = 1; $i <= 5; $i++) {
        User::create([
            'name' => "查询测试用户{$i}",
            'email' => "query_test{$i}_" . time() . "@example.com",
            'password' => "query{$i}"
        ]);
    }
    
    // 测试条件查询
    $users = User::query()
                ->where('name', 'like', '%查询测试%')
                ->orderBy('id', 'DESC')
                ->limit(3)
                ->get();
    
    if (!$users || !is_array($users) || count($users) === 0) {
        throw new \Exception("条件查询失败");
    }
    
    if (count($users) > 3) {
        throw new \Exception("limit条件无效");
    }
    
    echo "条件查询成功，找到 " . count($users) . " 个用户\n";
    
    // 测试聚合函数
    $count = User::query()->where('name', 'like', '%查询测试%')->count();
    
    if ($count < 5) {
        throw new \Exception("聚合函数count()测试失败");
    }
    
    echo "聚合函数测试成功，共有 {$count} 个查询测试用户\n";
    return true;
});

echo "\n测试完成\n";
echo "======================\n";